package com.tyl.xtk.config;

import cn.dev33.satoken.stp.StpInterface;
import com.tyl.xtk.beans.po.Permission;
import com.tyl.xtk.beans.po.Role;
import com.tyl.xtk.mapper.PermissionMapper;
import com.tyl.xtk.mapper.RoleMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义权限加载接口实现类
 */
@Component
public class StpInterfaceImpl implements StpInterface {

    @Resource
    RoleMapper roleMapper;
    
    @Resource
    PermissionMapper permissionMapper;

    /**
     * 返回一个账号所拥有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        long userId = (Long) loginId;
        List<Role> roles = roleMapper.selectByUserId(userId);
        
        List<String> permissions = new ArrayList<>();
        for (Role role : roles) {
            List<Permission> rolePermissions = permissionMapper.selectByRoleId(role.getId());
            for (Permission permission : rolePermissions) {
                permissions.add(permission.getCode());
            }
        }
        return permissions;
    }

    /**
     * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        long userId = (Long) loginId;
        List<Role> roles = roleMapper.selectByUserId(userId);
        return roles.stream().map(Role::getName).toList();
    }

}